package xyz.yolin.controller;


import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import xyz.yolin.pojo.Admin;
import xyz.yolin.service.AdminService;
import xyz.yolin.service.AdminServiceImpl;
import xyz.yolin.utils.MD5Utils;
import xyz.yolin.utils.MapControl;
import xyz.yolin.utils.SessionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {

    public static int currUser;
    @Autowired
//    @Qualifier("AdminServiceImpl")
    private AdminService adminService;

    @GetMapping("/login")
    public String login1(){
        return "login";
    }



    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    @PostMapping("/login")
    @ResponseBody
    public Map<String,Object> login(@RequestBody Map<String,Object> map, HttpServletRequest request){
        System.out.println(request);
        String account =map.get("username")+"";
        String password = map.get("password")+"";
        System.out.println(account+" "+password);
        if (Strings.isNullOrEmpty(account) || Strings.isNullOrEmpty(password)){
            return MapControl.getInstance().err("用户或密码不能为空").getMap();
        }
        Admin admin = adminService.login(account, MD5Utils.getMD5(password));

        currUser=admin.getId();
        System.out.println("查询出来的账户"+admin);
        if (admin!=null){
            HttpSession session = request.getSession();
//            session.setAttribute("admin",admin);
            SessionUtils.setAdmin(request,admin);
//            return
            return MapControl.getInstance().success().getMap();
        }else{
            return MapControl.getInstance().err("用户或密码错误").getMap();
        }
    }
}
